package com.example.paulzhang.rxjavatest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.internal.subscriptions.ArrayCompositeSubscription;
import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.ed_name)
    EditText mEdSearch;
    @BindView(R.id.tv_result)
    TextView mTvResult;
    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    //可以切换线程
    void testRxJava() {


        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                Log.d("1所在的线程============", Thread.currentThread().getName());
                Log.d("1发送的数据==========", "integer" + 1);
                emitter.onNext(1);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.d("2所在的线程=============", Thread.currentThread().getName());
                        Log.d("2接收的数据===========", "integer" + integer);
                    }
                });
    }

    @OnClick(R.id.bt_search)
    public void clickSearch() {
//        testRxJava();
        String searchText = mEdSearch.getText().toString();
        if (!TextUtils.isEmpty(searchText)) {
            testRxJavaAndRetrofit(searchText);
        }
    }

    @OnClick(R.id.bt_delete)
    public void clickDelete() {
        disposable.dispose();
    }

    void testRxJavaAndRetrofit(final String searchText) {
        Retrofit retrofit = create();
        final CityApi cityApi = retrofit.create(CityApi.class);
        Observable<AllCity> observable = cityApi.getAllCity("123");

        disposable = observable.subscribeOn(Schedulers.io())
                .flatMap(new Function<AllCity, ObservableSource<City>>() {
                    @Override
                    public ObservableSource<City> apply(AllCity allCity) throws Exception {
                        Log.d("flatMap============", Thread.currentThread().getName());
                        ArrayList<City> result = allCity.getResult();
                        return Observable.fromIterable(result);
                    }
                })
                .filter(new Predicate<City>() {
                    @Override
                    public boolean test(City city) throws Exception {
                        Log.d("filter============", Thread.currentThread().getName());
                        String labelName = city.getLabelName();
                        //字符串中包含查询的字符
                        if (labelName.indexOf(searchText) != -1) {
                            return true;
                        }

                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<City>() {
                    @Override
                    public void accept(City city) throws Exception {
                        Log.d("subscribe============", Thread.currentThread().getName());
                        mTvResult.setText(mTvResult.getText() + city.getLabelName());
                    }
                });



    }

    private static Retrofit create() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(10, TimeUnit.SECONDS);
        builder.connectTimeout(10, TimeUnit.SECONDS);

        return new Retrofit.Builder().baseUrl("http://v.juhe.cn/weather/")
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
    }
}
